package com.toket.android.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;

public class Util {
	
	public static final String ERROR_CODE_TIME_OUT = "408";
	public static final String ERROR_CODE_UNKNOW_HOST = "404";

	public final static int[] SELECTED = new int[] { android.R.attr.state_pressed };
	public final static int[] IDLE = new int[] { android.R.attr.state_enabled };
	
	public static StateListDrawable getImageButtonState(Bitmap selected, Bitmap idle){
		
	    StateListDrawable states = new StateListDrawable();

	    states.addState(SELECTED,new BitmapDrawable(selected)); 
	    states.addState(IDLE,new BitmapDrawable(idle));

	    return states;
	}

	public static StateListDrawable getImageButtonState(Drawable selected, Drawable idle){
		
	    StateListDrawable states = new StateListDrawable();

	    states.addState(SELECTED,selected); 
	    states.addState(IDLE,idle);

	    return states;
	}

	public static String toJSONString(String result){
		if(result.startsWith("("))
			return result.substring(1);
		if(!result.startsWith("{")){
			int index = result.indexOf("{");
			return result.substring(index);
		}
		
		else
			return result;
	}
	
	public static boolean isNullOrEmpty(String string) {
		if (string == null || string.length() == 0) {
			return true;
		}else{
			return false;
		}
	}
	
	public static void sendMessage(Context context, String address, String message) {
		Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms://"));
		sendIntent.putExtra("address", address);
		sendIntent.putExtra("sms_body", message);
		context.startActivity(sendIntent);
	}
	
	public static void sendEmail(Context context, String sender, String receiver, 
			String subject, String message){
	
		Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
		emailIntent.setType("plain/text"); 
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{receiver}); 
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); 
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); 
		context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
	}
	
	public static String getHttpGet(String url) {
		System.out.println("getHttpGet ===>>> " + url);
		HttpParams httpParameters = new BasicHttpParams();
		ConnManagerParams.setTimeout(httpParameters, 15000);
	    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
	    HttpConnectionParams.setSoTimeout(httpParameters, 15000);
	    
		StringBuilder str = new StringBuilder();
		HttpClient client = new DefaultHttpClient();  // new DefaultHttpClient(httpParameters); set time out
		HttpGet httpGet = new HttpGet(url);
		
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) { // Status OK
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
			} else {
				System.out.println("Failed to download result..");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str.toString();
	}
	
	public static String getHttpPost(String url,List<NameValuePair> params) {
		System.out.println("getHttpPost ===>>> " + url);
		HttpParams httpParameters = new BasicHttpParams();
		ConnManagerParams.setTimeout(httpParameters, 15000);
	    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
	    HttpConnectionParams.setSoTimeout(httpParameters, 15000);
	    
		StringBuilder str = new StringBuilder();
		HttpClient client = new DefaultHttpClient(); // new DefaultHttpClient(httpParameters); set time out
		HttpPost httpPost = new HttpPost(url);
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse response = client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) { // Status OK
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
			} else {
				System.out.println("Failed to download result..");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str.toString();
	}
	
	// http request
	public static String getHttpData(String url) {
		System.out.println("getUrlData ===>>> " + url);
		String result = null;
		int timeOutMS = 1000*10;
		
		try {
			URL myURL = new URL(url);
			URLConnection ucon = myURL.openConnection();
			ucon.setConnectTimeout(timeOutMS);
			InputStream is = ucon.getInputStream();
			result = convertStreamToString(is);
			is.close();
		} catch (Exception e) {
			   // TODO: handle exception
			   e.printStackTrace();
		}

		return result;
	}
	
	public static InputStream getJSONData(String url){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri;
        InputStream data = null;
        try {
            uri = new URI(url);
            HttpGet method = new HttpGet(uri);
            HttpResponse response = httpClient.execute(method);
            data = response.getEntity().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return data;
    }
	
	public static InputStream getInputStream(String url){

		System.out.println("getUrlData ====>>> " + url);
		
		int timeOutMS = 1000*10;
		InputStream is = null;
		
		try {
			URL myURL = new URL(url);
			URLConnection ucon = myURL.openConnection();
			ucon.setConnectTimeout(timeOutMS);
			is = ucon.getInputStream();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return is;
	}
	
	public static void openBrowser(Context ct, String url){
		Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(url));  
		ct.startActivity(viewIntent); 
	}
	
	public static void saveFileImage(Bitmap bitmap, String path){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
	    String date = dateFormat.format(new Date());
	    String photoFile = "Picture_" + date + ".png";
	    
	    File f = new File(path);
	    f.mkdirs();
	    
		try {
			FileOutputStream out = new FileOutputStream(new File(f, photoFile));
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
			out.flush();
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Bitmap getBitmap(String fileUrl) {
		  Bitmap bmImg = null;
		  
		  InputStream instream = null;
		  try {
		   
		   HttpGet httpRequest = null;
		   httpRequest = new HttpGet(fileUrl);

		   HttpClient httpclient = new DefaultHttpClient();
		   HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

		   HttpEntity entity = response.getEntity();
		   BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
		   instream = bufHttpEntity.getContent();
		   bmImg = BitmapFactory.decodeStream(instream);

		   instream.close();
		   instream = null;
		   
		   return bmImg;
		  } catch (Exception e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		   if(instream != null){
		    try {
		     instream.close();
		    } catch (IOException e1) {
		     // TODO Auto-generated catch block
		     e1.printStackTrace();
		    }
		    instream = null;
		   }
		  }
		  System.out.println("[getBitmap] done! : " + bmImg);
		  
		  return bmImg;
	}
	
	public static String convertStreamToString(InputStream is) {

		  StringBuilder sb = new StringBuilder();

		  try {
		   BufferedReader reader = new BufferedReader(new InputStreamReader(
		     is, "UTF-8"));
		   String line = null;
		   try {
		    while ((line = reader.readLine()) != null) {
		     sb.append(line + "\n");
		    }
		   } catch (IOException e) {
		    e.printStackTrace();
		   } finally {
		    try {
		     is.close();
		    } catch (IOException e) {
		     e.printStackTrace();
		    }
		   }
		  } catch (Exception e) {

		  }

		  return sb.toString();
	}
	
	public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
	
	public static Bitmap decodeScaledBitmapFromSdCard(String filePath,
            int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }
	
	public static boolean checkNetworkStatus(Context context)
    {
	    final ConnectivityManager connMgr = (ConnectivityManager)
	    context.getSystemService(Context.CONNECTIVITY_SERVICE);
	
	    final android.net.NetworkInfo wifi =
	    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	    
	    final android.net.NetworkInfo wimax =
		    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
	
	    final android.net.NetworkInfo mobile =
	    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	
	    if( wifi != null && wifi.isConnected() ){
//	    	Toast.makeText(context, "Wifi" , Toast.LENGTH_LONG).show();
	    }
	    else if( mobile != null && mobile.isConnected() ){
//	    	Toast.makeText(context, "Mobile 3G " , Toast.LENGTH_LONG).show();
	    }else if(wimax != null && wimax.isConnected()){
//	    	Toast.makeText(context, "Wimax " , Toast.LENGTH_LONG).show();
	    }
	    else
	    {
//	    	Toast.makeText(context, "You are offline." , Toast.LENGTH_LONG).show();
	    	return false;
    	}
	    
	    return true;
    }
	
}
